package com.maben.netty.udp.handler;

import cn.hutool.core.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Component;

/**
 * 自定义UPD处理类
 */
@Component
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        // 接收客户端发送的消息
        final ByteBuf content = packet.content();
        // 转换为byte[]
        int length = content.readableBytes();
        byte[] receivedBytes = new byte[length];
        // 读取数据到字节数组
        content.readBytes(receivedBytes);
        final String receiveHexStr = HexUtil.encodeHexStr(receivedBytes);
        System.out.println(Thread.currentThread()+",收到来自:" + packet.sender() + " 的消息,字节长度为:" + length + ",内容是: " + receiveHexStr);

        // 构建响应消息
        String response = "服务器已收到: " + receiveHexStr;
        DatagramPacket responsePacket = new DatagramPacket(
                Unpooled.copiedBuffer(response, CharsetUtil.UTF_8),
                packet.sender() // 发送给客户端
        );

        // 发送响应
        ctx.writeAndFlush(responsePacket);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
    